from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import *
from .serializers import *
# Create your views here.

class Register(APIView):
    def post(self,request):
        username = request.data['username']
        user = User.objects.filter(username=username)
        if user:
            request.session['username'] = username
            return Response({
                'code':200,
                'message':'欢迎光临'
            })
        else:
            return Response({
                'code':405,
                'message':'登录错误'
            })

class Show(APIView):
    def get(self,request):
        goods = Goods.objects.all()
        goodsl = Goodsser(goods,many=True)
        return Response({
            'data':goodsl.data
        })


class Addcart(APIView):
    def post(self,request):
        id = request.data['id']
        name = request.data['name']
        user = User.objects.filter(username=str(name)).first()
        goods = Goods.objects.filter(id=id).first()

        if int(user.user_level) == 1:
            prices = Youhui.objects.get(pk=1)
            price=int(goods.price)-int(prices.price)


        else:
            price = int(goods.price)
        Cart.objects.create(
            name = goods.title,
            price = price,
            uid = user
        )
        return Response({
            'price':price
        })

class Showcart(APIView):
    def post(self,request):
        name = request.data['name']
        uids = User.objects.filter(username=str(name)).first()
        cart = Cart.objects.filter(uid = uids)
        # cart = Cart.objects.all()
        carts = Cartser(cart,many=True)
        return Response({
            'data':carts.data
        })

